# admin.py
from django.contrib import admin
from django import forms
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from .models import Question, Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = '__all__'

class QuestionAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]
    form = QuestionForm
    
    # 表单布局优化
    fieldsets = [
        ('问题信息', {
            'fields': ['question_text', 'question_type'],
            'classes': ['wide'],
        }),
        ('发布日期', {
            'fields': ['pub_date'],
            'classes': ['collapse', 'wide'],
        }),
    ]
    
    inlines = [ChoiceInline]
    
    # 列表页显示优化
    list_display = ('question_text', 'pub_date', 'was_published_recently', 'choice_count', 'vote_link', 'question_type_display')
    list_display_links = ('question_text',)
    readonly_fields = ('vote_link',)
    list_filter = [
        ('pub_date', admin.DateFieldListFilter),
        'question_type',  # 添加问题类型过滤
    ]
    search_fields = ['question_text', 'choice__choice_text']
    list_per_page = 20
    actions = ['make_inactive']
    
    # 添加自定义列：选项数量
    def choice_count(self, obj):
        return obj.choices.count()
    choice_count.short_description = '选项数量'

    def vote_link(self, obj):
        from django.utils.html import format_html
        from django.urls import reverse
        if obj.id:
            return format_html('<a href="{}" target="_blank">查看投票</a>', reverse('polls:detail', args=[obj.id]))
        return format_html('<span style="color: #999;">保存后生成链接</span>')
    vote_link.short_description = '投票链接'
    
    # 显示问题类型
    def question_type_display(self, obj):
        return dict(Question.QUESTION_TYPES).get(obj.question_type, '普通')
    question_type_display.short_description = '问题类型'
    
    # 自定义保存时的消息
    def save_model(self, request, obj, form, change):
        question_type = form.cleaned_data.get('question_type')
        
        if question_type == 'latest':
            obj.pub_date = timezone.now()
            if not obj.question_text.startswith('最新投票: '):
                obj.question_text = '最新投票: ' + obj.question_text
        elif question_type == 'hot':
            if not obj.question_text.startswith('热门投票: '):
                obj.question_text = '热门投票: ' + obj.question_text
        
        obj.save()
        message = f'问题 "{obj.question_text}" 已成功保存。'
        self.message_user(request, message)

    def make_inactive(self, request, queryset):
        rows_updated = queryset.update(is_active=False)
        self.message_user(request, f'成功将 {rows_updated} 个问题设置为非活跃状态')
    make_inactive.short_description = '设置为非活跃'

admin.site.register(Question, QuestionAdmin)
admin.site.site_header = '投票系统'
admin.site.index_title = '系统管理首页'